//
//  MyCardListViewController.m
//  myhuibao
//
//  Created by 孙昕 on 14-2-20.
//  Copyright (c) 2014年 myhuibao. All rights reserved.
//

#import "MyCardListViewController.h"
#import "MyCardCell.h"
#import "LoadMoreCell.h"
#import "Config.h"
#import "SBJson.h"
#import "CardDetailViewController.h"
#import "OMGToast.h"
#import "HotSearchViewController.h"

@interface MyCardListViewController ()

@end

@implementation MyCardListViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    wqTable=_MainTable;
    delegate=self;
    // Do any additional setup after loading the view from its nib.
}

-(void)viewWillAppear:(BOOL)animated
{
    pageIndex=1;
    [self getMyCard];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void) getMyCard
{
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@?memberID=%d&password=%@&pageIndex=%d",url_mycardList,[[Config Instance] getMemberId],[[Config Instance] getPassword],pageIndex]] ;
    req = [ASIHTTPRequest requestWithURL:url];
    [req setShouldAttemptPersistentConnection:NO];
    [req setDelegate: self];
    [req setDidFinishSelector:@selector(finishMyCard:)];
    
    [req startAsynchronous];
}

- (void)finishMyCard:(ASIHTTPRequest *)request
{
    
    NSString *jsonStr = [request responseString];
    
    NSDictionary *dic = [jsonStr JSONValue];
    tableDataArray = [dic valueForKey:@"data"];
    if([tableDataArray count]==0)
    {
        [OMGToast showWithText:@"您暂未领取商户会员卡！" bottomOffset:100];
    }
    [_MainTable reloadData];
    returnCount=[tableDataArray count];
    [Config setExtraCellLineHidden:_MainTable];
}

- (IBAction)OnBack:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if([indexPath row] < ([tableDataArray count])) {
        return 100;
    }else{
        return 40;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	int count = [tableDataArray count];
    if (count>=pageSize) {
        return count+1;
    }else
        return count;
    return count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString *CellIdentifier = @"MyCardCellIdentifier";
    if([indexPath row] < ([tableDataArray count])) {
        
        MyCardCell *cell = (MyCardCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"MyCardCell" owner:nil options:nil];
            cell = [array objectAtIndex:0];
            [cell setSelectionStyle:UITableViewCellSelectionStyleGray];
        }
        
        NSMutableDictionary *item = [tableDataArray objectAtIndex:indexPath.row];
        cell.lbName.text=[item valueForKey:@"name"]==[NSNull null]?@"":[item valueForKey:@"name"];
        NSString * imageStr =[NSString stringWithFormat:@"%@%@",url_image, [item valueForKey:@"tempPath"]];
        [item setObject:[NSString stringWithFormat:@"%@",[item valueForKey:@"tempPath"]] forKey:@"image"];
        NSString *imageName =@"";
        if (![imageStr isEqual:[NSNull null] ]) {
            NSArray *array = [imageStr componentsSeparatedByString:@"/"];
            imageName = [array lastObject];
        }
        NSString *imageDataPath = [NSHomeDirectory() stringByAppendingPathComponent:[@"Library/Caches/" stringByAppendingString:imageName]];
        UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfFile:imageDataPath]];
        if (image) {
            CGRect rect =  CGRectMake(0, 0, image.size.width, image.size.height*2.0/3);
            CGImageRef cgimg = CGImageCreateWithImageInRect([image CGImage], rect);
            cell.ImageView.image = [UIImage imageWithCGImage:cgimg];
            CGImageRelease(cgimg);
        }
        else
        {
            cell.ImageView.image = [UIImage imageNamed:@"placeholder.png"];
            //placeholder为在未加载完成加载图片时显示的默认图片
        }
        
        return cell;
    }else{
        LoadMoreCell *cell = (LoadMoreCell *)[tableView dequeueReusableCellWithIdentifier: @"LoadMoreCellIdentifier"];
        if (cell==nil) {
            NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"LoadMoreCell" owner:nil options:nil];
            cell = [array objectAtIndex:0];
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        }
        if(returnCount<pageSize){
            cell.lbText.text=@"";
            cell.hidden = true;
        }else{
            //创建loadMoreCell
            cell.lbText.text=str_more;
        }
        cell.textLabel.textAlignment = UITextAlignmentCenter;
        cell.detailTextLabel.text=@"";
        cell.imageView.image =nil;
        return cell;
        
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    if (indexPath.row == [tableDataArray count]) {
        LoadMoreCell *loadMoreCell=(LoadMoreCell *)[tableView cellForRowAtIndexPath:indexPath];
        loadMoreCell.lbText.text=str_loading;
        //        [self performSelectorInBackground:@selector(loadMore) withObject:nil];
        //        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@?memberID=%d&password=%@&pageIndex=%d",url_mycardList,[[Config Instance] getMemberId],[[Config Instance] getPassword],++pageIndex]] ;
        req = [ASIHTTPRequest requestWithURL:url];
        [req setShouldAttemptPersistentConnection:NO];
        [req setDelegate: self];
        [req setDidFinishSelector:@selector(appendTableWith:)];
        [req startAsynchronous];
        return;
    }    //其他cell的事件
    else
    {
        NSMutableDictionary *item = [tableDataArray objectAtIndex:indexPath.row];
        if([[item objectForKey:@"publish"] intValue]==0)
        {
            [OMGToast showWithText:@"该会员卡商户已关闭" bottomOffset:100];
            return;
        }
        CardDetailViewController *view=[[CardDetailViewController alloc] initWithNibName:@"CardDetailViewController" bundle:nil];
        view.hidesBottomBarWhenPushed=YES;
        view.settingID=[[item objectForKey:@"settingID"] intValue];
        [self.navigationController pushViewController:view animated:YES];
    }
}

-(void) appendTableWith:(ASIHTTPRequest *)request
{   //将loadMore中的NSMutableArray添加到原来的数据源listData中.
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    NSMutableArray *data = [dic valueForKey:@"data"];
    returnCount=[data count];
    for (int i=0;i<[data count];i++) {
        [tableDataArray addObject:[data objectAtIndex:i]];
    }
    NSMutableArray *insertIndexPaths = [NSMutableArray arrayWithCapacity:pageSize];
    for (int ind = 0; ind < [data count]; ind++) {
        NSIndexPath    *newPath =  [NSIndexPath indexPathForRow:[tableDataArray indexOfObject:[data objectAtIndex:ind]] inSection:0];
        [insertIndexPaths addObject:newPath];
    }
    if ([data count]==0) {
        [_MainTable reloadData];
    }
    //重新调用UITableView的方法, 来生成行.
    [_MainTable insertRowsAtIndexPaths:insertIndexPaths withRowAnimation:UITableViewRowAnimationFade];
}


-(void)cellImageDidLoad:(NSIndexPath *)indexPath image:(UIImage *)image
{
    dispatch_async(dispatch_get_main_queue(), ^{
        MyCardCell *cell=(MyCardCell*)[wqTable cellForRowAtIndexPath:indexPath];
        //    cell.imageView.image = image;
        //cell.imageView.image = [image copy];
        if(image)
        {
            CGRect rect =  CGRectMake(0, 0, image.size.width, image.size.height*2.0/3);
            CGImageRef cgimg = CGImageCreateWithImageInRect([image CGImage], rect);
            cell.ImageView.image = [UIImage imageWithCGImage:cgimg];
            CGImageRelease(cgimg);
        }
    });
    

}

- (IBAction)OnAddCard:(id)sender {
    HotSearchViewController *view = [[HotSearchViewController alloc] initWithNibName:@"HotSearchViewController" bundle:nil] ;
    view.hidesBottomBarWhenPushed=YES;
    view.iHotType =HOTCARD;
    [[ self navigationController] pushViewController:view animated:YES];
}
@end
